<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe height="76vh">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1===0 ? 'bdtop' : '','vcenter']" 
            v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row :class="[ i2===0 ? '' : 'bdtop','vcenter']"
                 v-for="(item2,i2) in item1.children" :key="item2.id">
                    <el-col :span="8">
                      <el-tag  type="success"
                       closable @close="removeRightById(scope.row,item2.id)">
                        {{item2.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级权限 -->
                    <el-col :span="16">
                      <el-tag type="warning" closable 
                      @close="removeRightById(scope.row,item3.id)"
                      v-for="(item3) in item2.children" :key="item3.id">
                        {{item3.authName}}
                      </el-tag>                   
                    </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色操作" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-search" @click="editRoleShow(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row)">删除</el-button>
            <el-button size="mini" type="warning"
             icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleVisible"
      width="30%"
      @close="editRoleClosed">
      <el-form :model="roleInfo" ref="roleInfoRef" :rules="RoleRule">
        <el-form-item label="角色ID">
          <el-input v-model="roleInfo.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="setRightDialogClosed">
      <el-tree ref="treeRef" :data="rightList" :props="treeProps" show-checkbox
       node-key="id" default-expand-all :default-checked-keys="defKeys"
       > 
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      @close="addRoleColsed"
      width="40%">
      <el-form 
       :model="addRoleInfo"
       :rules="RoleRule"
       ref="addRoleRef"
       label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input  v-model="addRoleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRole = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data(){
    return{
      //所有角色列表数据
      roleList:[],
      //控制分配权限对话框的显示
      setRightDialogVisible:false,
      //所有权限的数据
      rightList:[],
      //树形控件的属性绑定对象
      treeProps:{
        label:'authName',
        children:'children'
      },
      //默认选中的节点id值
      defKeys:[],
      //当前即将分配角色的id
      roleId:'',

      //添加角色对话框的显示与隐藏
      addRoleDialogVisible:false,
      //添加的角色信息
      addRoleInfo:{
        roleName:'',
        roleDesc:''
      },
      //添加角色的验证规则
      RoleRule:{
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字之间',
            trigger: 'change'
          }
        ]
      },

      //编辑角色
      roleInfo:{},
      editRoleVisible:false,
    }
  },
  created(){
    this.getRolesList()
  },
  methods:{
    //编辑角色对话框的显示
    async editRoleShow(role){
      //查询角色信息
      const {data:res} = await this.$http.get(`roles/${role.id}`)
      if(res.meta.status !== 200) return this.$message.error('获取用户数据失败')
      this.roleInfo = res.data
      this.editRoleVisible = true
     },
    //提交角色信息
    async editRole(){
      const {data:res} = await this.$http. put(`roles/${this.roleInfo.roleId}`,{
        roleName:this.roleInfo.roleName,
        roleDesc:this.roleInfo.roleDesc
      })
      if(res.meta.status !== 200) return this.$message.error('编辑提交角色失败')
      this.$message.success('提交成功')
      this.getRolesList()
      this.editRoleVisible = false
    },
    //编辑角色对话框的关闭
    editRoleClosed(){
      this.$refs.roleInfoRef.resetFields()
    },

    //删除角色
    deleteRole(role){
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async () => {
          const {data:res} = await this.$http.delete(`roles/${role.id}`)
          if(res.meta.status !== 200){
            return this.$message.error('删除失败')
          }
          this.getRolesList()
          this.$message.success('删除成功')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    //添加角色
    addRole(){  
      //$ref预验证
      this.$refs.addRoleRef.validate(async valid => {
        if(!valid) return
        const {data:res} = await this.$http.post('roles',this.addRoleInfo)
        if(res.meta.status !== 201){
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        console.log(res.data)
        this.getRolesList()
      })
      
      this.addRoleDialogVisible = false
    },
    showAddRole(){
      this.addRoleDialogVisible = true
    },
    //添加角色对话框的关闭
    addRoleColsed(){
      //清空表单信息缓存
      this.$refs.addRoleRef.resetFields()
    },
    async getRolesList(){
      const {data:res} = await this.$http.get('roles')
      if(res.meta.status !== 200){
        return this.$message.error('获取角色列表失败')
      }
      //console.log(res.data)
      this.roleList = res.data
    },
    async removeRightById(role,rightId){
      //弹框提示用户是否要删除
      const confirmResult =  await 
      this.$confirm('此操作将永久删除文件，是否继续？','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
      }).catch(err => err)
      if(confirmResult !== 'confirm'){
        return this.$message.info('取消删除')
      }
      const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // this.$http.delete('roles/'+roleId+'/rights/'+rightId)
      if(res.meta.status !== 200){
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      // this.getRolesList()    //会全部重新渲染
      //为当前角色单独刷新渲染
      role.children = res.data
    },

    //分配权限
    async showSetRightDialog(role){
      this.roleId = role.id
      //获取所有权限列表的数据
      const {data:res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200){
        return this.$message.error('获取权限列表失败')
      }
      //把获取到的权限数据保存到data中
      this.rightList = res.data
      this.getLeafKeys(role,this.defKeys)
      //展示分配权限的对话框
      this.setRightDialogVisible = true
    },
    //通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node,arr){
      if(!node.children){
        //如果当前node不包含children属性，则是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item,arr))
    },
    //监听对话框的关闭事件
    setRightDialogClosed(){
     //先清空defKeys缓存
      this.defKeys = []
    },

    //点击为角色分配权限
    async allotRight(){
      //this.setRightDialogVisible = false
      const keys = [
        // "..." : 展开运算符(合并数组)
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //console.log(keys)
      const idStr = keys.join(',')
      const {data:res} = await 
        this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
      if(res.meta.status !== 200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top:1px solid #eee
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
